//package com.cabinet.payinterface.controller;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.TypeReference;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.cabinet.common.utils.RedisUtils;
//import com.cabinet.common.utils.StringUtils;
//import com.cabinet.modules.activity.service.ActivityOrderService;
//import com.cabinet.modules.api.service.CaseApiService;
//import com.cabinet.modules.api.service.MemberRechargeService;
//import com.cabinet.modules.card.service.MonthCardService;
//import com.cabinet.modules.withdrawal.entity.OrderChannelInfoEntity;
//import com.cabinet.modules.withdrawal.service.OrderChannelInfoService;
//import com.cabinet.payinterface.bean.RefundBean;
//import com.cabinet.payinterface.handler.impl.cmbc.utils.SignEncryptDncryptSignChk;
//import com.cabinet.payinterface.handler.impl.wxpay.utils.XmlUtils;
//import com.cabinet.payinterface.service.InterfacePayment;
//import com.cabinet.payinterface.utils.PaymentHelper;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.ResponseBody;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
//import java.nio.charset.StandardCharsets;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Properties;
//import java.util.function.Consumer;
//
///**
// * @author xueyou
// * @date 2021/3/26
// */
//@Slf4j
//@Controller
//@RequestMapping("/notify/cmbc")
//public class CbmbPayNotifyController {
//
//    @Resource
//    private CaseApiService caseApiService;
//
//    @Resource
//    private ActivityOrderService activityOrderService;
//
//    @Resource
//    private MemberRechargeService memberRechargeService;
//
//    @Resource
//    private OrderChannelInfoService orderChannelInfoService;
//
//    @Resource
//    RedisUtils redisUtils;
//
//    @Resource
//    private InterfacePayment interfacePayment;
//
//    @Resource
//    MonthCardService monthCardService;
//
//    /**
//     * 回调解密
//     */
//    private void callbackRes(HttpServletRequest request, HttpServletResponse response, String interfaceCode, Consumer<Map<String, String>> func) {
//        log.info("*************** 民生支付通知START ****************");
//        try (BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
//            String line;
//            StringBuilder sb = new StringBuilder();
//            while ((line = br.readLine()) != null) {
//                sb.append(line);
//            }
//            log.info("民生支付通知原文: [{}]", sb.toString());
//            Map<String,String> res = JSON.parseObject(sb.toString(), new TypeReference<HashMap<String,String>>() {});
//            OrderChannelInfoEntity orderChannelInfoEntity = orderChannelInfoService.getOne(new QueryWrapper<OrderChannelInfoEntity>().eq("code", interfaceCode));
//            if (orderChannelInfoEntity == null) {
//                throw new Exception("无效的接口编号: " + interfaceCode);
//            }
//            Properties properties = JSON.parseObject(orderChannelInfoEntity.getTradeConfigs(), new TypeReference<Properties>() {});
//            String merchantPrivateKey = properties.getProperty("merchantPrivateKey");
//            String merchantPwd = properties.getProperty("merchantPwd");
//            String cmbcPublicKey = properties.getProperty("cmbcPublicKey");
//            String dncryptContext = SignEncryptDncryptSignChk.dncrypt(res.get("context"), merchantPrivateKey, merchantPwd);
//            log.info("民生支付通知解密: [{}]", dncryptContext);
//            if (!SignEncryptDncryptSignChk.signCheck(dncryptContext, cmbcPublicKey)) {
//                log.error("民生支付签名验证失败");
//                response.getWriter().write("FAIL");
//                return;
//            }
//            Map<String,String> result = JSON.parseObject(dncryptContext, new TypeReference<HashMap<String,String>>() {});
//            Map<String, String> resMap = XmlUtils.getMapFromXml(result.get("body"));
//            log.info("民生支付通知解密: [{}]", resMap);
//
//            func.accept(resMap);
//
//            response.getWriter().write("SUCCESS");
//        } catch (Exception e) {
//            log.error("民生银行支付通知处理异常: ", e);
//            try {
//                response.getWriter().write("FAIL");
//            } catch (Exception ex) {
//                log.error("民生银行支付响应异常：", ex);
//            }
//        }
//    }
//
//    /**
//     * 民生银行扫码开箱通知接口 适用于小程序支付的结果通知
//     */
//    @RequestMapping(value = "/paynotify")
//    public void paynotify(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "interfaceCode") String interfaceCode) {
//        callbackRes(request, response, interfaceCode, (resMap) -> {
//            try {
//                caseApiService.openBoxPayNotify(PaymentHelper.cbmbNotifyConver(resMap));
//            } catch (Exception e) {
//                log.error("民生支付通知开箱异常", e);
//                throw new RuntimeException(e);
//            }
//        });
//    }
//
//    /**
//     * 活动支付通知接口
//     */
//    @RequestMapping(value = "/activityNotify")
//    public void activityNotify(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "interfaceCode") String interfaceCode) {
//        callbackRes(request, response, interfaceCode, (resMap) -> {
//            try {
//                //设置redis锁，不想重复通知
//                String outTradNo = resMap.get("orderNo");
//                String tradeNo = redisUtils.get(outTradNo);
//
//                if (StringUtils.isEmpty(tradeNo)) {
//                    redisUtils.set(outTradNo, tradeNo, 60 * 60);
//                    activityOrderService.activityPayComplete(PaymentHelper.cbmbNotifyConver(resMap));
//                }
//            } catch (Exception e) {
//                log.error("民生支付活动付款完成异常", e);
//                throw new RuntimeException(e);
//            }
//        });
//    }
//
//
//    /**
//     * 用户充值通知接口
//     */
//    @RequestMapping(value = "/rechargeNotify")
//    public void rechargeNotify(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "interfaceCode") String interfaceCode) {
//        callbackRes(request, response, interfaceCode, (resMap) -> {
//            try {
//                //设置redis锁，不想重复通知
//                String tradeNo = redisUtils.get(resMap.get("orderNo") + "-recharge");
//                if (StringUtils.isEmpty(tradeNo)) {
//                    redisUtils.set(resMap.get("orderNo") + "recharge", tradeNo);
//                    memberRechargeService.rechargePayComplete(PaymentHelper.cbmbNotifyConver(resMap));
//                }
//            } catch (Exception e) {
//                log.error("民生支付充值完成异常", e);
//                throw new RuntimeException(e);
//            }
//        });
//    }
//
//
//    /**
//     * 活动支付通知接口
//     */
//    @RequestMapping(value = "/cardNotify")
//    public void cardNotify(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "interfaceCode") String interfaceCode) {
//        callbackRes(request, response, interfaceCode, (resMap) -> {
//            try {
//                //设置redis锁，不想重复通知
//                String outTradNo = resMap.get("orderNo");
//                String tradeNo = redisUtils.get(outTradNo);
//
//                if (StringUtils.isEmpty(tradeNo)) {
//                    redisUtils.set(outTradNo, tradeNo, 60 * 60);
//                    monthCardService.cardPayComplete(PaymentHelper.cbmbNotifyConver(resMap));
//                }
//            } catch (Exception e) {
//                log.error("民生支付活动付款完成异常", e);
//                throw new RuntimeException(e);
//            }
//        });
//    }
//
//
//
//    /**
//     * 测试退款
//     */
//    @RequestMapping(value = "refund")
//    @ResponseBody
//    public void refund(@RequestParam String orderNo, @RequestParam Double amount, @RequestParam(required = false) String interfaceCode) {
//        RefundBean refundBean = new RefundBean();
//        refundBean.setAmount(amount);
//        refundBean.setInterfaceCode(StringUtils.isEmpty(interfaceCode) ? "CMBC-PAYMENT" : interfaceCode);
//        refundBean.setBillCode(orderNo);
//        refundBean.setRefundCode(orderNo);
//        refundBean.setRefundAmount(amount);
//        refundBean.setRemark("支付");
//        interfacePayment.refund(refundBean);
//    }
//
//    /**
//     * 测试查询
//     */
//    @RequestMapping(value = "query")
//    @ResponseBody
//    public Map<String, String> query(@RequestParam String orderNo, @RequestParam(required = false) String interfaceCode) {
//        Map<String, String> params = new HashMap<>();
//        params.put("billCode", orderNo);
//        params.put("interfaceCode", StringUtils.isEmpty(interfaceCode) ? "CMBC-PAYMENT" : interfaceCode);
//        return interfacePayment.query(params);
//    }
//
//    public static void main(String[] args) throws Exception {
//        String merchantPrivateKey = "/Users/xueyou/cunionpay/projects/cabinet/data/certs/cust0001.sm2";
//        String cmbcPublicKey = "/Users/xueyou/cunionpay/projects/cabinet/data/certs/cmbcTest.cer";
//        String merchantPwd = "123abc";
//        String businessContext = "MIIFKAYKKoEcz1UGAQQCA6CCBRgwggUUAgECMYGdMIGaAgECgBRXXvBVVWTiR6ARshCGukqaGyUKfzANBgkqgRzPVQGCLQMFAARwEHmzw3NwtFptoeNHbnhWaeDbQGb4m78tf1A5NKybZ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9jVFGVZyspjLQAfRprZGqT5Ijw9nN/rjVXR7KIwr+gCDco943PJ/NDE6E0zUd43PzHm91BUh1TzPbEwcECBiu6jxrenjxPcBwIC4lHUtu5KtDDuQJqehywL7SOo51dwo/y+Rq993fdz9EFWN9GAEfQWTgrG/WAQMGpGoA3mF4s8h/UiU5e51KrG/Cyh85sRjUFCIFMcImmkmbc+/x44wXQERVBduvgd7OtQ6Ds+536RLDfIaEMHCDvdOWEYdWZ51cf/EnegrsaSLaytGBzxg0UZS+DY+zzQTnNelpoB18fg48k3nXf9JAUmF+nIs2rCCutj3ax3Ux5POp1kb8Cioc9w4Wr85vvnxMZ17Y2ZErCC8MOzmMio5JS+bhrZu4nlcXeUIbILij/cAtb+BbitNKKvAEmP4kNrHflQ+tE8zSJ3dqhu5MIXIKqR8G+lbH5JlCccuwlZhN26/ZFoB0JGgq6wg1NF3gF4aFZsfktl4ZDpS+T/oGjK4AnoIDbLVEE2i8uvWBIutYDn8FM3WrllZ12kYjnHy+evGM4iUpmsw==";
//        String dncryptContext = SignEncryptDncryptSignChk.dncrypt(businessContext, merchantPrivateKey, merchantPwd);
//        log.info("民生支付请求成功响应: [{}]", dncryptContext);
//        if (!SignEncryptDncryptSignChk.signCheck(dncryptContext, cmbcPublicKey)) {
//            log.error("签名验证失败");
//        }
//        Map<String,String> result = JSON.parseObject(dncryptContext, new TypeReference<HashMap<String,String>>() {});
//        Map<String, String> resMap = XmlUtils.getMapFromXml(result.get("body"));
//        log.info("body = [{}]", resMap);
//
//    }
//
//}
